<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Services\ModuleService;
use App\Services\RoleService;
use Illuminate\Http\Request;
use \Exception;

class ModuleController extends Controller
{

    public const STATUS_ENABLE = 1;

    public const STATUS_DISABLE = 2;

    private $moduleService;

    private $roleService;

    public function __construct(ModuleService $moduleService, RoleService $roleService)
    {
        $this->moduleService = $moduleService;
        $this->roleService = $roleService;
    }

    public function index()
    {

    }

    /**
     * 获取用户模型
     *
     * @param Request $request
     * @return mixed
     */
    public function getModulesByRoleId(Request $request)
    {
        $page = [
            'page_name' => 'newRoles',
            'title' => '添加角色',
            'breadcrumb' => [
                [
                    'text' => '角色管理',
                    'url' => '/admin/newRoles'
                ]
            ],
        ];


        $roleModules =  empty($request->input('role_id')) ? [] : $this->roleService->getModulesByRoleId($request->input('role_id'));

        $modules = $this->moduleService->getModules();

        if (!empty($roleModules)) {
            $roleModuleIdArr = [];
            $roleMenuIdArr = [];
            foreach ($roleModules as $roleModule) {
                $roleModuleIdArr[] = $roleModule->module_id;
                $roleMenuIdArr[] = $roleModule->menu_id;
            }
        }

        return view('admin.module.role_modules',
            [
                'roleModules' => $roleModules ?? [],
                'modules' => $modules ?? [],
                'role_id' => $request->input('role_id') ?? 0,
                'menu_id_arr' => $roleMenuIdArr ?? [],
                'module_id_arr' => $roleModuleIdArr ?? [],
                'page' => $page,
            ]);
    }


    /**
     * 角色增加权限
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        try {
            $this->moduleService->addModule($request, $this->roleService->createRole($request));
        } catch (Exception $exception) {
            return response()->json([
                'code'  => 1,
                'msg'   => $exception->getMessage()
            ]);
        }

        return response()->json([
            'code'  =>   0,
            'msg'   => '更新成功'
        ]);
    }
}